package 剑指offer;

import java.util.ArrayList;

/**
 * Created by lenovo】 on 2017/2/19.
 */
public class PrintMatrix {

    public ArrayList<Integer> printMatrix(int[][] matrix) {

        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        int columns = matrix[0].length;
        int rows = matrix.length;
        int x = 0;
        int y = 0;

        if (columns == 1) {
            for (int i = 0; i < rows; i ++) {
                arrayList.add(matrix[i][0]);
            }
            return arrayList;
        }
        if (rows == 1) {
            for (int j = 0; j < columns; j++) {
                arrayList.add(matrix[0][j]);
            }
            return arrayList;
        }

        while (columns > 2 * x && rows > 2 * y) {
            print(arrayList, matrix, rows, columns, x, y);
            x++;
            y++;
        }
        if (columns == rows && columns % 2 != 0) {
            arrayList.add(matrix[columns / 2][columns / 2]);
        }
        // 去除多余
        // 原因是最后遍历的数组是一列或者一行会出现回路查询问题
        int len = arrayList.size();
        if (columns > rows && rows > 2) {
            int tmpc = columns - rows;
            for (int i = 1; i < tmpc; i++) {
                arrayList.remove(len - i);
            }
        }else if (rows > columns && columns > 2) {
            int tmpr = rows - columns;
            for (int j = 1; j < tmpr; j++) {
                arrayList.remove(len - j);
            }
        }
        return arrayList;
    }

    public void print(ArrayList<Integer> arrayLists, int[][] matrix, int rows, int columns, int x, int y) {

        int endx = x;
        int endy = y;
        int endX = columns - x - 1;
        int endY = rows - y - 1;
        for (; y < endX; y++) {
//            System.out.print(matrix[x][y]+ " ");
            arrayLists.add(matrix[x][y]);
        }
        for (;x < endY ;x++) {
//            System.out.print(matrix[x][y]+" ");
            arrayLists.add(matrix[x][y]);
        }
        for (;y > endy ;y--) {
//            System.out.print(matrix[x][y]+" ");
            arrayLists.add(matrix[x][y]);
        }
        for (;x > endx ;x--) {
//            System.out.print(matrix[x][y]+" ");
            arrayLists.add(matrix[x][y]);
        }
    }
}